package com.zndroid.logcat.core;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by lzy on 2021/1/15.
 */
public final class LogcatManager {
    private ExecutorService executor;
    private LogcatMapper mapper;

    public void start(LogcatMapper.IMapper listener) {
        if (null == executor) {
            executor = new ThreadPoolExecutor(1, 1,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>(10), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        }
        if (null == mapper) {
            mapper = new LogcatMapper(listener);
        }
        setRead(true);

        if (!executor.isShutdown()) {
            executor.execute(mapper);
        }
    }

    public void pause() {
        setRead(false);
    }

    public void resume() {
        setRead(true);
        if (null != executor && !executor.isShutdown()) {
            executor.execute(mapper);
        }
    }

    public void close() {
        setRead(false);
        if (!executor.isShutdown()) {
            executor.shutdown();
        }
        executor = null;
        mapper = null;
    }

    public void clean() {
        mapper.clean();
    }

    public void setRead(boolean read) {
        if (null != mapper) {
            mapper.setReading(read);
        }
    }

    /////
    /**
     * not allow new instance
     * */
    private LogcatManager(){}

    private static class M { private static final LogcatManager MM = new LogcatManager();}

    public static LogcatManager getInstance() {
        return M.MM;
    }
}
